package cn.nawang.ebeim.api.controller;

import cn.nawang.ebeim.api.comm.BaseController;
import cn.nawang.ebeim.api.domain.User;
import cn.nawang.ebeim.api.domain.UserLoginCode;
import cn.nawang.ebeim.api.service.*;
import cn.nawang.ebeim.api.utils.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: LoginController
 * @Description: 登录模块的控制器
 * @author fanyb
 * @date Aug 11, 2015 11:33:39 AM
 * @version v1.0
 */
@RestController
public class LoginController extends BaseController {
  private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

  @Autowired
  private UserService userService;

  @Autowired
  private CaService caService;

  // @Autowired
  // private TokenManager tokenManager;

  @Autowired
  private CustomerService customerService;

  @Autowired
  private AuthorizationCheckService authorizationCheckService;

  @Autowired
  private HeartLogService heartLogService;
  /**
   * 
   * @author fanyb
   * @Description: 用户登录
   * @param username 用户名
   * @param password 密码
   * @param request
   * @return Map 用户登录信息
   * @date Aug 12, 201510:05:32 AM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public Map<String, Object> login(String username, String password, HttpServletRequest request) {
    LOG.debug("/login {}", username, password);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("token", "");
    map.put("code", Constant.CODE_ERROR);
    boolean flag = false;
    // 判断输入的次数是否超过了规定的次数(2)次
    String idCode = request.getParameter("code");// 接收前端页面输入的验证码
    UserLoginCode userLoginCode = (UserLoginCode) request.getSession().getAttribute(username);
    if (userLoginCode == null || userLoginCode.getPwdFalseCount() < 2) {
      flag = true;
    }

    // 输入错误次数超过了两次
    if (!flag) {
      String validateC = (String) request.getSession().getAttribute("validateCode");// 获取生成验证码时放在session中的验证码
      if (idCode == null || "".equals(idCode)) {
        map.put("flag", flag);
        map.put("message", "验证码为空");
        return map;
      }
      if (!idCode.toLowerCase().equals(validateC.toLowerCase())) {// 验证码不区分大小写
        map.put("flag", flag);
        map.put("message", "验证码不正确");
        return map;
      }
    }
    map = userService.findUserByUsernameAndPwd(username, password, request);
    if (userLoginCode != null && userLoginCode.getPwdFalseCount() == 1) {
      flag = false;
    }
    map.put("flag", flag);
    // 登录出错进行的操作
    if ((Integer) map.get("code") == Constant.CODE_ERROR) {
      if (userLoginCode == null) {
        userLoginCode = new UserLoginCode();
        userLoginCode.setId(username);
        userLoginCode.setPwdFalseCount(0);
      }
      userLoginCode.setPwdFalseCount(userLoginCode.getPwdFalseCount() + 1);
      request.getSession().setAttribute(username, userLoginCode);
    }
    if (map.get("user") != null) {
      User user = (User) map.get("user");
      // 判断用户是否修改过默认的密码，如果没有则不存在session中
      if (!user.getIsUpdateDefaultPwd().equals(Constant.USER_IS_FIRST_LOGIN_YES)) {
        this.setUserLoginInfo(request, user);
      }
      // 创建token
      // String httpToken = tokenManager.createdToken().getToken();
      String httpToken = "";
      map.put("token", httpToken);
      map.put("code", Constant.CODE_SUCCESS);
    }
    LOG.debug("login {}", map);
    return map;
  }

  /**
   * @author 张建峰
   * @Description: ui端登入
   * @param @param user
   * @param @param request
   * @param @return
   * @return Map<String,Object>
   * @date 2015年10月9日上午10:25:36
   *
   * @修改人 张建峰
   * @修改日期
   */
  @RequestMapping(value = "/web_ui/login", method = RequestMethod.GET)
  public Map<String, Object> webUiLogin(String username, String password,
      HttpServletRequest request) {
    LOG.info("/login {}", username, password, request);
    request.getSession().setAttribute("validateCode", "web_ui_login_code_200");
    Map<String, Object> map = login(username, password, request);
    User user = (User) map.get("user");
    if (user != null) {
      map.put("statics", heartLogService.getMemoryAll(user));
      map.put("backuptimes", heartLogService.getBackupTimes(user.getId()));
      map.put("serverInfo", heartLogService.getServerTimes(user.getLabId()));
      map.put("ca", caService.findByLabId(user.getLabId()));
      map.put("customer", customerService.findOne(user.getCustomerId()));
      // 授权时间是否过期
      authorizationCheckService.isOverAuthTime(map, username);
      // 空间大小是否达到预警值
      authorizationCheckService.isOverCapacity(map, username);
    }
    LOG.debug("webUiLogin {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 根据用户id获取到用户的统计信息
   * @param userId
   * @param request
   * @return Map<String,Object> 
   * @date Nov 10, 20155:13:05 PM
   *
   * @修改人 
   * @修改日期
   */
  @RequestMapping(value = "/token/web_ui/first_page", method = RequestMethod.GET)
  public Map<String, Object> webUiFirstPage(String userId, HttpServletRequest request) {
    LOG.info("/web_ui/first_page {}", userId, request);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", Constant.CODE_ERROR);
    User user = userService.findOne(userId);
    if (user != null) {
      map.put("statics", heartLogService.getMemoryAll(user));
      map.put("backuptimes", heartLogService.getBackupTimes(user.getId()));
      map.put("serverInfo", heartLogService.getServerTimes(user.getLabId()));
      map.put("ca", caService.findByLabId(user.getLabId()));
      map.put("customer", customerService.findOne(user.getCustomerId()));
    }else{
      map.put("desc", "用户不存在");
      return map;
    }
    map.put("code", Constant.CODE_SUCCESS);
    LOG.debug("webUiFirstPage {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: token失败返回的结果
   * @return Map<String,Object>
   * @date Sep 24, 201511:55:54 AM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/login/token_expired")
  public Map<String, Object> tokenExpired(HttpServletResponse response) {
    LOG.debug("/login/token_expired {}");
    Map<String, Object> map = new HashMap<String, Object>();
    String message = response.getHeader("message");
    if (message.equals(Constant.HTTP_TOKEN_VERIFY_ZERO)) {
      map.put("code", Constant.CODE_ERROR);
      map.put("message", Constant.HTTP_TOKEN_VERIFY_RESULT.get(Constant.HTTP_TOKEN_VERIFY_ZERO));
    } else if (message.equals(Constant.HTTP_TOKEN_VERIFY_ONE)) {
      map.put("code", Constant.CODE_ERROR);
      map.put("message", Constant.HTTP_TOKEN_VERIFY_RESULT.get(Constant.HTTP_TOKEN_VERIFY_ONE));
    } else if (message.equals(Constant.HTTP_TOKEN_VERIFY_TWO)) {
      map.put("code", Constant.CODE_ERROR);
      map.put("message", Constant.HTTP_TOKEN_VERIFY_RESULT.get(Constant.HTTP_TOKEN_VERIFY_TWO));
    } else if (message.equals(Constant.HTTP_TOKEN_VERIFY_THREE)) {
      map.put("code", Constant.CODE_ERROR);
      map.put("message", Constant.HTTP_TOKEN_VERIFY_RESULT.get(Constant.HTTP_TOKEN_VERIFY_THREE));
    }
    LOG.debug("tokenExpired {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 登录失败返回的接口
   * @return Map<String,Object>
   * @date Sep 24, 201511:56:59 AM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/login/fail")
  public Map<String, Object> loginFail() {
    LOG.debug("/login/fail {}");
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", Constant.CODE_ERROR);
    map.put("message", "请先登录");
    LOG.debug("loginFail {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 退出登录
   * @param request
   * @return Object
   * @date Oct 10, 20155:52:45 PM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/logout")
  public Map<String, Object> logoutWeb(HttpServletRequest request) {
    LOG.debug("/logout {}");
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", Constant.CODE_ERROR);
    request.getSession().removeAttribute("user");
    map.put("code", Constant.CODE_SUCCESS);
    LOG.debug("logoutWeb {}", map);
    return map;
  }
  
  @RequestMapping(value = "/token/monitor/userInfo", method = RequestMethod.GET)
  public Map<String, Object> monitorUserInfo(String id,String spaceSize,String labId,HttpServletRequest request) {
    LOG.info("/monitorUserInfo {}",  request);
    request.getSession().setAttribute("validateCode", "web_ui_login_code_200");
    Map<String, Object> map = new HashMap();
   User user=new User();
   user.setSpaceSize(spaceSize);
   user.setId(id);
    if (user != null) {
      map.put("statics", heartLogService.getMemoryAll(user));
      map.put("serverInfo", heartLogService.getServerTimes(labId));
    }
    
    
    LOG.debug("webUiLogin {}", map);
    return map;
  }
}
